package com.swim.webuser.web;

import cn.hutool.core.lang.Assert;
import com.jeesite.common.codec.DesUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Extend;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.msg.SmsUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sys.dao.EmployeeDao;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.swim.common.responseobject.ResponseObject;
import com.swim.common.utils.SmsUtil;
import com.swim.sys.entity.SysUserRole;
import com.swim.sys.service.SysUserRoleService;
import com.swim.webuser.bean.WebUserLoginBean;
import com.swim.webuser.service.WebUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;


/**
 * @Author tql
 * @Description WebUserController
 * @Date 21-2-27 下午8:35
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping(value = "${adminPath}/web/user")
public class WebUserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private WebUserService webUserService;

    private String code = "";

    /**
     * 用户注册
     */
    @PostMapping(value = "/register")
    @ResponseBody
    public String register(@Validated WebUserLoginBean webUserLoginBean) {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(now);
        User u = new User();
        u.setIsNewRecord(true);
        u.setLoginCode(webUserLoginBean.getUsername());
        u.setUserName(webUserLoginBean.getUsername());
        u.setPassword(webUserLoginBean.getPassword());
        u.setMobile(webUserLoginBean.getUsername());
        u.setUserType("employee");
        u.setMgrType(User.MGR_TYPE_NOT_ADMIN);
        u.setRefCode(webUserLoginBean.getUsername());
        u.setRefName(webUserLoginBean.getUsername());
//        u.setPwdQuestion(webUserLoginBean.getCode()); //todo bug
        u.setPwdQuestionAnswer(formattedDate);
        userService.save(u);
//        User ue = new User();
//        ue.setLoginCode(webUserLoginBean.getUsername());
//        Extend uee = new User().getExtend();
//        uee.setExtendS1(webUserLoginBean.getCode());
//        uee.setExtendS2(formattedDate);
//        ue.setExtend(uee);
//        userService.update(ue);
        //新增员工（jeesite中的员工表）
        Employee employee = new Employee();
        employee.setEmpCode(u.getUserCode());
        employee.setEmpName(webUserLoginBean.getUsername());
        Office office = new Office();
        office.setOfficeCode("natatorium_students");
        office.setOfficeName("游泳学员");
        employee.setOffice(office);
        employee.setCorpCode("0");
        employee.setCorpName("JeeSite");
        employeeDao.insert(employee);
        //新增用户角色关系数据
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserCode(u.getUserCode());
        sysUserRole.setRoleCode("user");//普通用户
        sysUserRoleService.insertUserRole(sysUserRole);
        return renderResult(Global.TRUE, text("用户注册成功！"));
    }

    /**
     * 对验证码进行验证: 2025/2/7
     *
     * @return
     */
    @GetMapping(value = "/check/verification/code")
    @ResponseBody
    public String checkVerificationCode() {
        User user = UserUtils.getUser();
        try {
            Assert.notNull(user.getExtend(), "处理失败");
            Date date = new Date();
            date.setTime(1l);
            user.getExtend().setExtendD1(date);
            userService.save(user);
        } catch (Exception e) {
            log.error("-------------------  验证码失效失败  ----------------------");
            log.error(e.getMessage());
            return renderResult(Global.FALSE, text(e.getMessage()));
        }
        return renderResult(Global.TRUE, text("验证码校验成功"));
    }

    @PostMapping(value = "/check/verification/code")
    @ResponseBody
    public void verificationCode() {

    }

    /**
     * 手机验证码
     *
     * @param mobile
     * @return
     */
    @GetMapping(value = "/verification/code")
    @ResponseBody
    public String verificationCode(@Validated @RequestParam String mobile) {
        try {
            if (!org.springframework.util.StringUtils.hasText(mobile)) {
                return this.renderResult("true", "手机号为空，请输入手机号!");
            }
            // 查询用户信息
            User u = new User();
            u.setLoginCode(mobile);
            User user = userService.getByLoginCode(u);
            if (user != null) {
                return this.renderResult("true", "手机号已经注册，请直接登录!");
            } else {
                Random random = new Random();
                code = "";
                for (int i = 0; i < 6; i++) {
                    code += random.nextInt(10);
                }
                // 发送验证码
                SmsUtil.Get(mobile, code);
                // 更新信息: 2025/2/7
                Extend extend = new Extend();
                extend.setExtendS1(code);
                extend.setExtendD1(new Date());
                user.setExtend(extend);
                userService.update(user);
            }
        } catch (Exception e) {
            System.out.println("发送异常");
        }
        return renderResult(Global.TRUE, text("手机验证码发送成功"));
    }

//    @GetMapping(value = "/check/verification/code")
//    @ResponseBody
//    public String checkVerificationCode(@Validated @RequestParam String verificationCode) {
//        if (!Optional.ofNullable(verificationCode).isPresent()) {
//            return renderResult(Global.FALSE, text("验证码不得为空"));
//        }
//        if (code.equals(verificationCode)) {
//            return renderResult(Global.TRUE, text("验证码校验成功"));
//
//        }
//        return renderResult(Global.FALSE, text("验证码校验失败"));
//    }

//    @GetMapping(value = "/check/verification/code")
//    @ResponseBody
//    public String checkVerificationCode(@Validated @RequestParam String verificationCode) {
//        return renderResult(Global.TRUE, text("验证码校验成功"));
//    }

    /**
     * 根据userCode获取游泳馆信息Id
     */
    @GetMapping(value = "getNatatoriumInfoIdByUserCode")
    @ResponseBody
    public String getNatatoriumInfoIdByUserCode(String userCode) {
        String natatoriumInfoId = webUserService.getNatatoriumInfoIdByUserCode(userCode);
        return renderResult(Global.TRUE, text("获取游泳馆信息Id成功"), natatoriumInfoId);
    }

    /**
     * 根据UserCode查询该用户的角色RoleCode
     *
     * @return roleCode
     */
    @ResponseBody
    @RequestMapping(value = "findRoleCodeByUserCode")
    public String findRoleCodeByUserCode(String userCode) {
        String roleCode = "";
        List<String> roleCodeList = sysUserRoleService.findRoleCodeByUserCode(userCode);
        if (roleCodeList != null && roleCodeList.size() > 0) {
            roleCode = roleCodeList.get(0);
            //如果角色中有游泳馆管理员角色则返回游泳馆管理员角色
            for (String roleCodeOne : roleCodeList) {
                if ("natatoriumAdmin".equals(roleCodeOne)) {
                    roleCode = "natatoriumAdmin";
                }
            }
        }
        return roleCode;
    }

    /**
     * 根据userName获取简单登录令牌
     *
     * @param userName 登录名(数据库中的 login_code字段)
     */
    @RequestMapping(value = "getLoginToken")
    @ResponseBody
    public String getLoginToken(String userName) {
        String token = UserUtils.getSsoToken(userName);
        return renderResult(Global.TRUE, text("获取登录令牌成功！"), token);
    }

    @RequestMapping(value = "sendSms")
    @ResponseBody
    public String sendSms(HttpServletRequest request) {
        String mobile = request.getParameter("mobile");
        String type = request.getParameter("type"); // 0忘记密码
        if (StringUtils.isBlank(mobile)) {
            return this.renderResult("true", "手机号为空，请输入手机号!");
        }
        User findUser = new User();
        findUser.setMobile(mobile);
        findUser.setStatus("0");
        List<User> list = this.userService.findList(findUser);
        if (CollectionUtils.isEmpty(list)) {
            return this.renderResult("true", "当前手机号没有注册请检查!");
        }
        User user = list.get(0);
        String title = "";
        try {
            String fpValidCode = StringUtils.getRandomNum(6);
            title = user.getUserName() + "（" + user.getLoginCode() + "）" + title + "验证码";
            String content = "您好，您的验证码是：" + fpValidCode + "（请勿透露给其他人）感谢您的使用。";
            SmsUtils.send(content, mobile);
            SmsUtil.forgetPwd(mobile, fpValidCode);
            // 更新验证码
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = sdf.format(now);
            User ue = new User();
            ue.setUserCode(mobile);
            ue.setPwdQuestion(fpValidCode);
            ue.setPwdQuestionAnswer(formattedDate);
            userService.updateQuestion(ue);
            /*HttpSession session = request.getSession();
            if ("1".equals(type)) {
                session.setAttribute("fpValidCode3" + mobile, fpValidCode);
            } else {
                session.setAttribute("fpValidCode2" + mobile, fpValidCode);
            }*/
        } catch (Exception e) {
            logger.error(title + "发送短信错误。", e);
            return renderResult(Global.FALSE, "系统出现了点问题，错误信息：" + e.getMessage());
        }
        return this.renderResult("true", "发送验证码成功");
    }

    @RequestMapping(value = "changePwd")
    @ResponseBody
    public String changePwd(HttpServletRequest request) {
        String mobile = request.getParameter("mobile");
        String sms = request.getParameter("sms");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        if (StringUtils.isBlank(mobile)) {
            return this.renderResult("true", "请输入您的手机号!");
        }
        if (StringUtils.isBlank(sms)) {
            return this.renderResult("true", "请输入您的验证码!");
        }
        if (StringUtils.isBlank(password)) {
            return this.renderResult("true", "请输入您的密码!");
        }
        if (StringUtils.isBlank(confirmPassword)) {
            return this.renderResult("true", "请输入您的确认密码!");
        }
        if (!confirmPassword.equals(password)) {
            return this.renderResult("true", "您的确认密码和密码不一致，请重新输入!");
        }
        /*HttpSession session = request.getSession();
        Object mobileSmsObj = session.getAttribute("fpValidCode2" + mobile);
        if (mobileSmsObj == null) {
            return this.renderResult("true","您还没有发送验证码，请发送验证码!");
        }
        String mobileSms = mobileSmsObj.toString();*/
        User findUser = new User();
        findUser.setMobile(mobile);
        findUser.setStatus("0");
        List<User> list = this.userService.findList(findUser);
        if (CollectionUtils.isEmpty(list)) {
            return this.renderResult("true", "当前手机号没有注册请检查!");
        }
        User user = list.get(0);
        if (!sms.equals(user.getPwdQuestion())) {
            return this.renderResult("true", "您的验证码输入错误，请重新输入!");
        }

        String secretKey = Global.getProperty("shiro.loginSubmit.secretKey");
        if (StringUtils.isNotBlank(secretKey)) {
            String encodePwd = DesUtils.encode(password, secretKey);
            user.setPassword(encodePwd);
        } else {
            String encodePwd = userService.encryptPassword(password);
            user.setPassword(encodePwd);
        }
        // this.userService.update(user);
        this.userService.updatePassword(mobile, password);
        return this.renderResult("true", "重置新密码成功");
    }

    @RequestMapping(value = "loginWithSms")
    @ResponseBody
    public ResponseObject<User> loginWithSms(HttpServletRequest request) {
        ResponseObject<User> responseObject = new ResponseObject<>();
        String mobile = request.getParameter("mobile");
        String sms = request.getParameter("sms");
        if (StringUtils.isBlank(mobile)) {
            responseObject.setCode(1);
            responseObject.setMessage("请输入您的手机号!");
            return responseObject;
        }
        if (StringUtils.isBlank(sms)) {
            responseObject.setCode(1);
            responseObject.setMessage("请输入您的验证码!");
            return responseObject;
        }
        User findUser = new User();
        findUser.setMobile(mobile);
        findUser.setStatus("0");
        List<User> list = this.userService.findList(findUser);
        if (CollectionUtils.isEmpty(list)) {
            responseObject.setCode(4);
            responseObject.setMessage("当前手机号没有注册请检查!");
            return responseObject;
        }
        User user = list.get(0);
        if (!sms.equals(user.getPwdQuestion())) {
            responseObject.setCode(3);
            responseObject.setMessage("您的验证码输入错误，请重新输入!");
            return responseObject;
        }
        responseObject.setCode(0);
        responseObject.setData(user);
        responseObject.setMessage("登录成功");
        return responseObject;
    }

    //@RequiresPermissions("user")
    @PostMapping(value = "userInfo/updateLoginCode")
    @ResponseBody
    public String updateLoginCode(User user, HttpServletRequest request) {
        String var10002;
        String[] var10003;
        boolean var10005;
        String loginCode2 = request.getParameter("loginCode2");
        if (StringUtils.isBlank(user.getUserName())) {
            //var10002 = NetStat.int("u+u|s!c ('u7t\u001cg?c\u001ci&D>g<m");
            var10005 = true;
            var10003 = new String[0];
            var10005 = true;
            return this.renderResult("true", "用户昵称不能为空");
        } else {
            User findUser = new User();
            if (!loginCode2.equals(user.getLoginCode())) {
                findUser.setLoginCode(user.getLoginCode());
                findUser.setStatus("0");
                List<User> list = this.userService.findList(findUser);
                if (CollectionUtils.isNotEmpty(list)) {
                    return this.renderResult("true", "登录账号已存在请检查!");
                }
            }

            User a = UserUtils.getUser();
            a.setAvatarBase64(user.getAvatarBase64());
            a.setUserName(user.getUserName());
            a.setEmail(user.getEmail());
            a.setMobile(user.getMobile());
            a.setPhone(user.getPhone());
            a.setSex(user.getSex());
            a.setSign(user.getSign());
            a.setLoginCode(user.getLoginCode());
            this.userService.update(a);
            //var10002 = Extend.int("\u0004\u0015\u0004B\u0002\u001f\u0012\u001eY\u0005\u0019\n\u0018?\u0016\u001a\u0012?\u0002\u000f\u0014\t\u0004\u001f");
            var10005 = true;
            var10003 = new String[0];
            var10005 = true;
            return this.renderResult("true", "修改用户code成功");
        }
    }

}
